package yawning.mew.pivot;

import org.apache.pivot.collections.HashMap;
import org.apache.pivot.collections.Map;
import org.apache.pivot.collections.List;
import org.apache.pivot.json.JSON;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.ComponentMouseButtonListener;
import org.apache.pivot.wtk.Mouse;
import org.apache.pivot.wtk.Mouse.Button;
import org.apache.pivot.wtk.TableView;

//
// On Mouse Click handler for the TableViews that use an "enabled" checkbox.
// Blatantly stolen from the Pivot examples.
//

public class MewTableViewMouseButtonListener implements ComponentMouseButtonListener  {
	@SuppressWarnings("unchecked")
	@Override
	public boolean mouseClick(Component component, Mouse.Button button, int x, int y, int count) {
		if (button == Mouse.Button.LEFT) {
			TableView tableView = (TableView) component;

			int columnIndex = tableView.getColumnAt(x);
			// TODO: The column name should be specified in the constructor or something.
			if (tableView.getColumns().get(columnIndex).getName().equals("enabled")) {
				int rowIndex = tableView.getRowAt(y);
				List<Map<String,Object>> data = (List<Map<String,Object>>) tableView.getTableData();
				Map<String,Object> row = new HashMap<String,Object>((Map<String,Object>)data.get(rowIndex));
//				Map<String,?> row = data.get(rowIndex); // XXX: Need to copy here, or data.update() takes a fast path.

				boolean enabled = (Boolean) JSON.get(row, "enabled");
				JSON.put(row, "enabled", !enabled);

				data.update(rowIndex, row);
			}
		}
		return false;
	}

	@Override
	public boolean mouseDown(Component arg0, Button arg1, int arg2, int arg3) {
		return false;
	}

	@Override
	public boolean mouseUp(Component arg0, Button arg1, int arg2, int arg3) {
		return false;
	}
}
